package com.lc.user.express.ordering;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptor;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.LatLngBounds;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.PoiItem;
import com.lc.user.express.BaseSecondActivity;
import com.lc.user.express.MainActivity;
import com.lc.user.express.R;
import com.lc.user.express.app.AppContext;
import com.lc.user.express.httpserver.GetAutoSelectDriver;
import com.lc.user.express.httpserver.GetOrderCancel;
import com.lc.user.express.httpserver.GetUserOrdering;
import com.lc.user.express.utils.GetToast;
import com.lc.user.express.utils.PublicMethod;
import com.lc.user.express.view.CustomDigitalClock;
import com.lc.user.express.view.dialog.AffirmDialog;
import com.zcx.helper.http.AsyCallBack;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/3/24. 派单中
 */
public class SendingOrderActivity extends BaseSecondActivity implements AMap.OnInfoWindowClickListener, AMap.InfoWindowAdapter {
    public static final String SHOW_SELECT_DIVER = "com.lc.user.express.show.select.diver";//跳转选择司机页面广播
    private BroadcastReceiver mReceiver;
    private AMap aMap;
    private MapView mapView;

    private TextView tv_addr;//地址
    private CustomDigitalClock tv_time;//计时
    private String point = "";//发货地经纬度
    private LatLng slatLng;//发货地经纬度

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sending_order);
        setTitle("派单中");
        setRightButtonText("取消订单", 150);
        tv_time = (CustomDigitalClock) findViewById(R.id.tv_time);
        tv_time.setStartTime(System.currentTimeMillis());
        tv_addr = (TextView) findViewById(R.id.tv_addr);

        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        init();
        registerReceiver();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.head_right:
                new AffirmDialog(cnt, "您确定要取消该订单吗？", "取消", "确定", R.style.MyDialog) {

                    @Override
                    protected void onYesClick() {
                        // TODO Auto-generated method stub
                        cancelOrder();
                    }
                }.show();
                break;
        }
    }

    private void cancelOrder() {
        new GetOrderCancel(AppContext.myPreferences.getUid(), getIntent().getStringExtra("orderid"), new AsyCallBack<Object>() {
            @Override
            public void onSuccess(String toast, int type, Object info) throws Exception {
                super.onSuccess(toast, type, info);
                show(MainActivity.class);
                sendBroadcast(new Intent(MainActivity.SWICH_FRAGMENT));
                finish();
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                if (!TextUtils.isEmpty(toast)) GetToast.useString(cnt, toast);
            }
        }).execute(cnt);//调接口
    }

    /**
     * 初始化AMap对象
     */
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
            aMap.setOnInfoWindowClickListener(this);// 设置点击infoWindow事件监听器
            aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
            aMap.getUiSettings().setZoomControlsEnabled(false);//隐藏放大缩小按钮
            aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
            aMap.moveCamera(CameraUpdateFactory.zoomTo(11));

//            tv_addr.setText(getIntent().getStringExtra("start_addr"));
            point = getIntent().getStringExtra("spoint");
            String[] s = point.split(",");
            slatLng = new LatLng(PublicMethod.strToDouble(s[0]), PublicMethod.strToDouble(s[1]));//添加发货地址marker
            aMap.addMarker(new MarkerOptions()
                    .position(slatLng)
                    .icon(BitmapDescriptorFactory.fromBitmap(
                            BitmapFactory.decodeResource(getResources(), R.mipmap.addr_start))));
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(slatLng));
            addMark();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
//        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
    }

    @Override
    public void onBackPressed() {
        new AffirmDialog(cnt, "离开该页面，您将无法选择司机，是否离开？", "取消", "离开", R.style.MyDialog) {

            @Override
            protected void onYesClick() {
                //finish();
                // TODO Auto-generated method stub
                showOrderFragment();
                autoSelectDriver();
            }
        }.show();
    }

    private void autoSelectDriver() {

        new GetAutoSelectDriver(AppContext.myPreferences.getUid(), getIntent().getStringExtra("orderid"), new AsyCallBack<Object>() {
            @Override
            public void onSuccess(String toast, int type, Object info) throws Exception {
                super.onSuccess(toast, type, info);
                showOrderFragment();
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                if (!TextUtils.isEmpty(toast)) GetToast.useString(cnt, toast);
            }
        }).execute(cnt);//调接口

    }

    private void showOrderFragment() {
        show(MainActivity.class);
        sendBroadcast(new Intent(MainActivity.SWICH_FRAGMENT));
        finish();
    }

    private myPoiOverlay poiOverlay;// poi图层
    private List<PoiItem> poiItems = new ArrayList<>();// poi数据

    private void addMark() {
        new GetUserOrdering(point, AppContext.myPreferences.getCityId(), getIntent().getStringExtra("orderid"), getIntent().getStringExtra("cid"), new AsyCallBack<GetUserOrdering.Info>() {
            @Override
            public void onSuccess(String toast, int type, GetUserOrdering.Info info) throws Exception {

                poiItems.addAll(info.dataList);

                if (poiItems != null && poiItems.size() > 0) {
                    poiOverlay = new myPoiOverlay(aMap, poiItems);
                    poiOverlay.addToMap();
                    poiOverlay.zoomToSpan();
                } else {
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(slatLng));
                }

            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);

            }
        }).execute(cnt, false);


    }

    @Override
    public View getInfoWindow(Marker marker) {
        View view = getLayoutInflater().inflate(
                R.layout.map_null_order, null);
        return view;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {

    }

    private class myPoiOverlay {
        private AMap mamap;
        private List<PoiItem> mPois;
        private ArrayList<Marker> mPoiMarks = new ArrayList<Marker>();

        public myPoiOverlay(AMap amap, List<PoiItem> pois) {
            mamap = amap;
            mPois = pois;
        }

        /**
         * 添加Marker到地图中。
         *
         * @since V2.1.0
         */
        public void addToMap() {
            handler.postDelayed(runnable, 0);
        }

        int count = 0;
        Handler handler = new Handler();
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                // handler自带方法实现定时器
                try {
                    if (count < mPois.size()) {
                        Marker marker = mamap.addMarker(getMarkerOptions(count));
                        PoiItem item = mPois.get(count);
                        marker.setObject(item);
                        mPoiMarks.add(marker);
                        handler.postDelayed(this, 1000);
                        count++;
                    } else {
                        handler.removeCallbacks(runnable);
                    }

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    System.out.println("exception...");
                }
            }
        };

        /**
         * 去掉PoiOverlay上所有的Marker。
         *
         * @since V2.1.0
         */
        public void removeFromMap() {
            for (Marker mark : mPoiMarks) {
                mark.remove();
            }
        }

        /**
         * 移动镜头到当前的视角。
         *
         * @since V2.1.0
         */
        public void zoomToSpan() {
            if (mPois != null && mPois.size() > 0) {
                if (mamap == null)
                    return;
                LatLngBounds bounds = getLatLngBounds();
                mamap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100));
//                mamap.moveCamera(CameraUpdateFactory.changeLatLng(slatLng));
            }
        }

        private LatLngBounds getLatLngBounds() {
            LatLngBounds.Builder b = LatLngBounds.builder();
            for (int i = 0; i < mPois.size(); i++) {
                b.include(new LatLng(mPois.get(i).getLatLonPoint().getLatitude(),
                        mPois.get(i).getLatLonPoint().getLongitude()));
            }
            b.include(slatLng);
            return b.build();
        }

        private MarkerOptions getMarkerOptions(int index) {
            return new MarkerOptions()
                    .position(
                            new LatLng(mPois.get(index).getLatLonPoint()
                                    .getLatitude(), mPois.get(index)
                                    .getLatLonPoint().getLongitude()))
                    .title(getTitle(index)).snippet(getSnippet(index))
                    .icon(getBitmapDescriptor());
        }

        protected String getTitle(int index) {
            return mPois.get(index).getTitle();
        }

        protected String getSnippet(int index) {
            return mPois.get(index).getSnippet();
        }

        /**
         * 从marker中得到poi在list的位置。
         *
         * @param marker 一个标记的对象。
         * @return 返回该marker对应的poi在list的位置。
         * @since V2.1.0
         */
        public int getPoiIndex(Marker marker) {
            for (int i = 0; i < mPoiMarks.size(); i++) {
                if (mPoiMarks.get(i).equals(marker)) {
                    return i;
                }
            }
            return -1;
        }

        /**
         * 返回第index的poi的信息。
         *
         * @param index 第几个poi。
         * @return poi的信息。poi对象详见搜索服务模块的基础核心包（com.amap.api.services.core）中的类 <strong><a href="../../../../../../Search/com/amap/api/services/core/PoiItem.html" title="com.amap.api.services.core中的类">PoiItem</a></strong>。
         * @since V2.1.0
         */
        public PoiItem getPoiItem(int index) {
            if (index < 0 || index >= mPois.size()) {
                return null;
            }
            return mPois.get(index);
        }

        protected BitmapDescriptor getBitmapDescriptor() {

            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(
                    BitmapFactory.decodeResource(getResources(), R.mipmap.cars));
            return icon;
        }


    }


    private void registerReceiver() {
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                String action = intent.getAction();
                if (action == null) {
                    return;
                }
                if (action.equals(SHOW_SELECT_DIVER)) {
//                    if(MyReceiver.orderid.equals(getIntent().getStringExtra("orderid"))){
                    Bundle bundle = new Bundle();
                    bundle.putString("orderid", getIntent().getStringExtra("orderid"));
                    bundle.putString("spoint", getIntent().getStringExtra("spoint"));
                    show(SelectDriverActivity.class, bundle);
                    finish();
//                    }

                }
            }
        };

        // 动态注册广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(SHOW_SELECT_DIVER);
        registerReceiver(mReceiver, intentFilter);
    }

}
